package current.eating;

import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class DiningPhilosophersDeadlockAllLock {

    ReentrantLock lock = new ReentrantLock();

    Phi[] phis = new Phi[5];
    // 叉子
    volatile int[] forks = new int[5];

    public DiningPhilosophersDeadlockAllLock() {
        for (int i = 0; i < 5; i++) {
            phis[i] = new Phi(i + 1);
            forks[i] = 0;
        }
    }


    class Phi extends Philosophy {
        public Phi(int id) {
            super(id);
        }

        @Override
        protected synchronized boolean takeLeft(int[] forks) {
            return super.takeLeft(forks);
        }

        @Override
        protected synchronized boolean takeRight(int[] forks) {
            return super.takeRight(forks);
        }

        @Override
        public void run() {
            while (true) {
                try {
                    this.thinking();
                    // 相当于单机运行，性能下降
                    lock.lockInterruptibly();
                    while (!this.takeLeft(forks)) {
                        Thread.onSpinWait();
                    }
                    while (!this.takeRight(forks)) {
                        Thread.onSpinWait();
                    }
                    lock.unlock();

                    this.eating();
                    this.putLeft(forks);
                    this.putRight(forks);
                    this.finish();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void run() {
        var pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            pool.submit(phis[i]);
        }
    }

    public static void main(String[] args) {
        var solver = new DiningPhilosophersDeadlockAllLock();
        solver.run();
    }
}
